﻿using PortUsedKill.Model.CustomException;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PortUsedKill
{
    static class Program
    {
        public static ApplicationContext context;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int SW_RESTORE = 9;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //处理未捕获的异常   
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常   
                Application.ThreadException += Application_ThreadException;
                //处理非UI线程异常   
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                Process currentProcess = Process.GetCurrentProcess();
                string processName = currentProcess.ProcessName;
                Process[] processes = Process.GetProcessesByName(processName);
                //如果该数组长度大于1，说明多次运行
                //currentProcess.Threads.Count;
                if (processes.Length > 1)
                {
                    var process = processes.FirstOrDefault(p => p.Id != currentProcess.Id);
                    if (process != null)
                    {
                        // 激活窗口
                        IntPtr hWnd = process.MainWindowHandle;
                        if (hWnd != IntPtr.Zero)
                        {
                            ShowWindow(hWnd, SW_RESTORE);
                            SetForegroundWindow(hWnd);
                        }
                    }
                }
                else
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    context = new ApplicationContext();
                    //注册程序运行空闲去执行主程序窗体相应初始化代码
                    Application.Idle += Application_Idle;
                    Application.Run(context);
                }
            }
            catch (ErrorTipException ex)
            {
                new UIForm().ShowErrorTip(ex.Message);
            }
            catch (Exception ex)
            {
                new UIForm().ShowErrorDialog(ex.Message);
            }
        }
        private static void Application_Idle(object sender, EventArgs e)
        {
            Application.Idle -= Application_Idle;
            if (context.MainForm == null)
            {
                Form form = new PortMainFrm();
                context.MainForm = form;
                form.Show();
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            ErrorTipException errorTipException = e.Exception as ErrorTipException;
            if (errorTipException != null)
            {
                new UIForm().ShowErrorTip(errorTipException.Message);
                return;
            }
            var ex = e.Exception;
            new UIForm().ShowErrorDialog("系统出现异常",ex.Message);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            new UIForm().ShowErrorDialog("系统出现异常C", ex.Message);
        }
    }
}
